package com.csf.config;

import com.csf.util.CommunityActivation;
import com.csf.util.communityUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityActivation {
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers(
                    "/discuss/insertDis",
                    "/like","/letter","/letterdetail/**"
                    ,"/insertMessage","/notice/list","/notice/detail/**",
                    "/user/**"
            )
                .hasAnyAuthority(
                        TYPE_ADMIN,
                        TYPE_USER,
                        TYPE_BZ
                )
                .antMatchers(
                        "/discuss/top",
                        "/discuss/wonderful"
        )
                .hasAnyAuthority(
                        TYPE_BZ
                )
                .antMatchers(
                        "/discuss/deleteDis",
                        "/data","/totalua","getdua"
                )
                .hasAnyAuthority(
                        TYPE_ADMIN
                )
                .anyRequest().permitAll()
//                取消设置csrf
                .and().csrf().disable();

//        权限不够时的处理
        http.exceptionHandling()
//                没有登录时的处理
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        String requestHeader = request.getHeader("x-requested-with");
//                        判断消息头是异步请求还是普通请求
                        if ("XMLHttpRequest".equals(requestHeader)){
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(communityUtils.getJsonString(403,"您还没有登录哦！"));
                        }else {
                            response.sendRedirect("/login");
                        }
                    }
                })
//                登录之后但是访问了没有权限的界面的处理
        .accessDeniedHandler(new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                String requestHeader = request.getHeader("x-requested-with");
                if ("XMLHttpRequest".equals(requestHeader)){
                    response.setContentType("application/plain;charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(communityUtils.getJsonString(403,"您还没有权限访问此页面！"));
                }else {
                    response.sendRedirect("/deny");
                }
            }
        });
//        退出登录处理，因为security会对退出进行默认处理，而我是想要自己来处理登出逻辑，所以为了实现自己的登出逻辑，必须覆盖掉默认的逻辑
        http.logout().logoutUrl("/securityLogout");
    }
}
